<template>
	<!-- detail-write-off?id=1361 -->
	<rh-wx class="my-card-list-container">
		<template>
			<view class="info-content flex-normal">
				<image class="tx-content" :src="baseData['headPortrait']" mode=""></image>
			  <view class="info-main flex-between">
					<view class="flex-column">
						<text class="user-name">{{baseData['userNickName']}}</text>
						<text class="user-tel">手机号：{{baseData['phone']}}</text>
					</view>
					<view class="btn-txt" @click="logout">
						退出登录
					</view>
			  </view>
			</view>
			<view class="tab-content">
			  <rh-tabs :list="tabList" @change-tab="tabChange" :scrollable="true"></rh-tabs>
			</view>
			<view class="card-list" v-if="currentTab.list">
				<view class="card-item flex-normal" v-for="(item, index) in currentTab.list" :key="index" 
					@click="jumpDatail(item)">
					<image class="card-icon" :src="item.coverUrl" mode="aspectFill"></image>
				  <view class="card-main flex-column">
				    <text class="card-label">{{item.activityName}}</text>
						<template v-if="currentTab['params_list'].orderStatus == '3'">
							<text class="card-status error">待激活</text>
						</template>
						<template v-if="currentTab['params_list'].orderStatus == '4'">
							<text class="card-desc">剩余次数：{{item.residueCount}}</text>
						</template>
						<template v-if="currentTab['params_list'].orderStatus == '8'">
							<text v-if="item.status == 1" class="card-status error">待兑换</text>
							<text v-else class="card-status">已兑换</text>
						</template>
						<template v-if="currentTab['params_list'].orderStatus == '6'">
							<text v-if="item.status == 7" class="card-status info">已退款</text>
							<text v-else class="card-status info">已失效</text>
						</template>
						<template v-if="currentTab['params_list'].orderStatus == '5'">
							<text class="card-status info">已核销</text>
						</template>
				    <text class="card-time" v-if="currentTab['params_list'].orderStatus == '5'">
							核销日期：{{item.verificationTime}}
						</text>
				    <text class="card-time" v-else>
							截止日期：{{item.endTime}}
						</text>
				  </view>
				</view>
				<view class="bottText" v-if="currentTab.list.length != 0">
					{{ currentTab['loadingText'] }}
				</view>
				<rh-no-content v-else></rh-no-content>
			</view>
		</template>
	</rh-wx>
</template>

<script>
	import {getWxCode, getUrlCode, isWechat, replaceWxUrl} from '@/script/wx-premission.js'
	import {getWxUserInfo, getUserInfo} from '@/api/common/index.js'
	import {getCardList} from '@/api/card/index.js'
	import wechat from '@/script/wechat.js'
	import { mapActions } from 'vuex'
	const TABLIST = [
		{idx: 0, isLoadMore: true, loadingText: '', name: "待激活", list: [], params_list: {pageNum: 1, pageSize: 10, orderStatus: '3'}},
		{idx: 1, isLoadMore: true, loadingText: '', name: "我的卡券", list: [], params_list: {pageNum: 1, pageSize: 10, orderStatus: '4'}},
		{idx: 2, isLoadMore: true, loadingText: '', name: "兑换券", list: [], params_list: {pageNum: 1, pageSize: 10, orderStatus: '8'}},
		{idx: 3, isLoadMore: true, loadingText: '', name: "已失效", list: [], params_list: {pageNum: 1, pageSize: 10, orderStatus: '6'}},
		{idx: 4, isLoadMore: true, loadingText: '', name: "已核销", list: [], params_list: {pageNum: 1, pageSize: 10, orderStatus: '5'}},
	]
	export default {
		data() {
			return {
				isWechat: isWechat,
				baseData: {},
				tabList: TABLIST,
				needRegister: false,
				currentTab: TABLIST[0]
			}
		},
		// 下拉刷新
		async onPullDownRefresh() {
			let _self = this;
			if(!this.isWechat) return
			let isSuccess = await _self.wxLogin()
			if(!isSuccess) return
			_self.currentTab.params_list["pageNum"] = 1;
			_self.initPage();
		},
		// 上拉加载
		onReachBottom() {
			let _self = this;
			if(!this.isWechat) return
			// 当前 TAB 上拉 锁定
			if (_self.currentTab.isLoadMore) {
				_self.currentTab.params_list.pageNum++;
				_self.queryCardList();
			}
		},
		async mounted() {
			let _self = this
			if(!this.isWechat) return
			let isSuccess = await _self.wxLogin()
			if(!isSuccess) return
			_self.initPage()
		},
		methods: {
			...mapActions(['setLocation']),
			wxLogin(){
				return new Promise(async (resolve, reject) => {
					let _self = this
					const token = uni.getStorageSync('ICarddWx') || ''
					if(token) return resolve(true)
					let code = getUrlCode('code')
					if(!code){
						getWxCode(location.href)
					}else{
						let isSuccess = await _self.getWxUserInfo(code).catch((err) => {
							let data = err.data
							if(data.code == 501){
								replaceWxUrl()
								getWxCode(location.href)
							}
						})
						resolve(isSuccess)
					}
				})
			},
			async getWxUserInfo(code) {
				let _self = this, isSuccess = false
				_self.needRegister = false
				await getWxUserInfo({code}).then(res => {
					let {isRegister = false, token} = res.data	
					let {name} = _self.$$router.getRoute(_self), location = {}
					let {query } = _self.$route
					if(isRegister){
						uni.setStorage({
							key: `icar-wxuser`,
							data: {...res.data},
							success: () => {
								_self.$$router.replace({name: 'registerTel', query:{
									redirect: name
								}})
							}
						})
					}else{
						uni.setStorage({
							key: `ICarddWx`,
							data: token,
						})
						isSuccess = true
					}
				}).finally(() => {
					replaceWxUrl()
				})
				return isSuccess
			},
			initPage(){
				let _self = this
				_self.setLocation()
				_self.queryUserInfo()
				_self.queryCardList()
			},
			jumpDatail(item){
				let _self = this, name = '', query = {id: item.id}
				let {orderStatus} = _self.currentTab['params_list']
				if(orderStatus == 4) { //待核销
					name = 'cardDetailWriteOff'
				}else if(orderStatus == 3) { // 待激活
					name = 'cardDetailActivation'
				}else if(orderStatus == 8) { // 兑换
					name = 'cardDetailExchange'
				}else if(orderStatus == 6) { // 已失效
					// name = 'cardDetailWriteOff'
				}
				if(!name) return
				_self.$$router.push({name, query}, (res) => {
					// window.location.reload()
				})
			},
			tabChange(tab){
				let _self = this
				_self.currentTab = tab
				let {pageNum} = tab.params_list
				if(pageNum == 1){
					_self.queryCardList()
				}
			},
			queryUserInfo(){
				let _self = this, isSuccess = false
				getUserInfo().then(res => {
					let {headPortrait, userNickName, phone} = res.data
					_self.baseData = {headPortrait, userNickName, phone}
					_self.$set(_self.baseData, 'headPortrait', headPortrait)
					_self.$set(_self.baseData, 'userNickName', userNickName)
					_self.$set(_self.baseData, 'phone', phone)
				})
			},
			queryCardList(){
				let _self = this, isSuccess = false
				_self.currentTab.isLoadMore = true
				getCardList(_self.currentTab.params_list).then(res => {
					let {rows = [], total} = res
					const { pageSize } = _self.currentTab.params_list
					if(pageSize >= total){
						_self.currentTab.list = res.rows
						_self.currentTab.isLoadMore = false
						_self.currentTab.loadingText = '我也是有底线的...'
					}else{
						_self.currentTab.list = [..._self.currentTab.list, ...rows]
						if(_self.currentTab.list.length >= total){
							_self.currentTab.isLoadMore = false
							_self.currentTab.loadingText = '我也是有底线的...'
						}else{
							_self.currentTab.loadingText = '再拉试试看...'
						}
					}
				}).finally(() => {
					uni.stopPullDownRefresh()
				})
			},
			logout(){
				let _self = this
				uni.removeStorage({
					key: `icar-wxuser`,
					success: () => {
						_self.$$router.replace({name: 'appLogin'})
					}
				})
			}
		}

	}
</script>
<style lang="scss" scoped>
  // @include fontStyle(#666, 24rpx);
	@mixin fontStyle($color, $size, $weight: 500) {
		color: $color;
		font-size: $size;
		font-weight: $weight;
	}
	.my-card-list-container{
		background-color: #F4F8F9;
		min-height: 100vh;
    padding: 0 20rpx;
    .info-content{
      padding-top: 100rpx;
      align-items: center;
			.tx-content{
				width: 72rpx;
				height: 72rpx;
				border-radius: 12rpx;
				overflow: hidden;
				background-color: #fff;
			}
			.info-main{
				margin-left: 40rpx;
				flex: 1;
				.user-name{
					@include fontStyle(#3E3E3E, 32rpx);
				}
				.user-tel{
					@include fontStyle(#C4C4C4, 24rpx);
				}
				.btn-txt{
					@include fontStyle(#3E3E3E, 32rpx);
				}
			}
    }
		.tab-content{
			margin-top: 20rpx;
		}
    .card-list{
      margin-bottom: 20rpx;
      .card-item{
        margin-top: 30rpx;
        background-color: #fff;
        border-radius: 20rpx;
        padding: 26rpx 20rpx;
        .card-icon{
          width: 228rpx;
          height: 144rpx;
          overflow: hidden;
          border-radius: 12rpx;
          background-color: #F4F8F9;
        }
        .card-main{
          flex: 1;
          margin-left: 30rpx;
          .card-label{
            @include fontStyle(#3E3E3E, 32rpx);
          }
          .card-desc{
            margin-top: 15rpx;
            @include fontStyle(#000000, 24rpx);
          }
					.card-status{
						margin-top: 15rpx;
						@include fontStyle(#3D3D3D, 24rpx);
						&.error{
							color: #D10909;
						}
					}
          .card-time{
            margin-top: 15rpx;
            @include fontStyle(#7F7F7F, 24rpx);
          }
        }
      }
    }
	}

</style>

